﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using c_work.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Work.Models;

namespace Work.Controllers
{
    [Route("[Controller]/[Action]")]
    [ApiController]
    public class PermissionsController : ControllerBase
    {
        private readonly DBContext _context;

        public PermissionsController(DBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取全部信息
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetPermissions()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            var list= await _context.Permissions.ToListAsync();
            dic.Add("data",list);
            dic.Add("code",0);
            return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Permission>> GetPermission(int id)
        {
            var permission = await _context.Permissions.FindAsync(id);

            if (permission == null)
            {
                return NotFound();
            }
            return permission;
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> PutPermission(int id, Permission permission)
        {
            if (id != permission.Id)
            {
                return BadRequest();
            }
            _context.Entry(permission).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PermissionExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return NoContent();
        }

        [HttpPost]
        public async Task<ActionResult<Permission>> PostPermission(Permission permission)
        {
            _context.Permissions.Add(permission);
            await _context.SaveChangesAsync();
            return CreatedAtAction("GetPermission", new { id = permission.Id }, permission);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePermission(int id)
        {
            var permission = await _context.Permissions.FindAsync(id);
            if (permission == null)
            {
                return NotFound();
            }
            _context.Permissions.Remove(permission);
            await _context.SaveChangesAsync();
            return NoContent();
        }

        private bool PermissionExists(int id)
        {
            return _context.Permissions.Any(e => e.Id == id);
        }
    }
}
